import { asyncRoutes, constantRoutes, pages } from '@/router'
import request from '@/utils/request'
import { loginApi } from '@/api/api'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some((role) => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach((route) => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  userBtnList: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
  SET_USER_BTN: (state, userBtnList) => {
    state.userBtnList = userBtnList
  }
}

//数组转树
const arrayToTree = (array, { id = 'id', pid = 'pid', children = 'children', rootId = null } = {}) => {
  const tree = array
  tree.forEach((item) => {
    var index = tree.findIndex((item1) => item1[id] === item[pid])
    if (index !== -1) {
      tree[index][children] = tree[index][children] || []
      tree[index][children].push(item)
    }
  })
  return tree.filter((item) => item[pid] === rootId)
}

const actions = {
  async generateRoutes({ commit }) {
    const { data } = await request(loginApi.getStaffMenuList)
    // 菜单
    let routes = data.filter((item) => {
      return (item.status && pages[item.component] && item.menuType === '2') || item.menuType === '5'
    })
    // 按钮或字段
    let btnOrFieldsRoutes = data.filter((item) => {
      return item.status && (item.menuType === '3' || item.menuType === '4')
    })
    commit('SET_USER_BTN', btnOrFieldsRoutes)

    routes = routes.map((item) => {
      const tmp = {}

      const firstChildren = routes.find((item2) => item2.parentId === item.id)
      if (firstChildren) {
        tmp.redirect = firstChildren.component
        tmp.path = firstChildren.component.replace(/(.*)+(\/[^/]+)/g, '$1')
      } else {
        tmp.path = item.component
      }
      tmp.component = pages[item.component]
      tmp.name = item.id
      tmp.meta = {}
      tmp.meta.title = item.name
      tmp.meta.icon = item.icon
      tmp.parentId = item.parentId
      tmp.id = item.id
      // 二级页面不显示在左侧菜单栏
      tmp.hidden = item.menuType === '5' ? true : false
      return tmp
    })

    routes = arrayToTree(routes, { pid: 'parentId', rootId: '0' })
    routes = routes.concat(asyncRoutes)
    return new Promise((resolve) => {
      commit('SET_ROUTES', routes)
      resolve(routes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
